<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <view class="px-6 pt-12 pb-4 flex items-center justify-between border-b border-gray-100">
      <view class="flex items-center">
        <view class="text-blue-500 mr-3" @click="goBack">
          <text class="fas fa-chevron-left"></text>
        </view>
        <view class="text-xl font-bold">
          {{ collectionInfo.name }}
        </view>
      </view>
      <view class="flex items-center space-x-4">
        <view class="text-gray-600 hover:text-gray-800" @click="shareCollection" id="shareButton">
          <text class="fas fa-share-alt text-xl"></text>
        </view>
      </view>
    </view>

    <!-- 收藏集信息 -->
    <view class="px-6 py-4 bg-gradient-to-br from-purple-500 to-pink-500 text-white">
      <view class="flex items-center justify-between">
        <view>
          <view class="text-2xl font-bold mb-2">{{ collectionInfo.name }}</view>
          <view class="text-sm opacity-90 mb-3">{{ collectionInfo.patterns.length }}个精选图案</view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="px-6 py-4 bg-gray-50 border-b border-gray-100">
      <view class="flex space-x-3">
        <view 
          class="flex-1 bg-blue-500 text-white py-3 px-4 rounded-xl font-medium play-button flex items-center justify-center"
          @click="playAllPatterns"
        >
          <text class="fas fa-play mr-2"></text>
          <text>立即播放全部</text>
        </view>
        <view 
          class="bg-white border border-gray-200 text-gray-700 py-3 px-4 rounded-xl"
          @click="addAllToPlaylist"
        >
          <text class="fas fa-plus"></text>
        </view>
      </view>
    </view>

    <!-- 图案列表 -->
    <scroll-view class="flex-1 px-6 py-4" scroll-y="true">
      <view class="space-y-3">
        <view 
          v-for="(pattern, index) in collectionInfo.patterns" 
          :key="pattern.id"
          class="bg-white rounded-xl p-4 flex items-center border border-gray-100 pattern-card"
        >
          <view class="w-16 h-16 bg-gray-100 rounded-lg flex items-center justify-center mr-4">
            <image 
              :src="pattern.image" 
              :alt="pattern.name" 
              class="w-full h-full object-cover rounded-lg"
              mode="aspectFill"
            />
          </view>
          <view class="flex-1">
            <view class="font-medium text-gray-900">{{ pattern.name }}</view>
            <view class="text-sm text-gray-500">{{ pattern.duration }}</view>
          </view>
          <view class="flex items-center space-x-2">
            <view 
              class="w-10 h-10 bg-blue-500 text-white rounded-full flex items-center justify-center hover:bg-blue-600 transition-colors"
              @click="playPattern(pattern)"
            >
              <text class="fas fa-play text-sm"></text>
            </view>
            <view 
              class="w-10 h-10 bg-gray-100 text-gray-600 rounded-full flex items-center justify-center hover:bg-gray-200 transition-colors"
              @click="addToPlaylist(pattern)"
            >
              <text class="fas fa-plus text-sm"></text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部导航栏 -->
    <view class="h-20 border-t border-gray-200 flex items-center justify-around px-6">
      <view class="flex flex-col items-center text-gray-400 hover:text-blue-500 transition-colors" @click="goHome">
        <text class="fas fa-home text-xl"></text>
        <text class="text-xs mt-1">设备</text>
      </view>
      <view class="flex flex-col items-center text-blue-500" @click="goExplore">
        <text class="fas fa-compass text-xl"></text>
        <text class="text-xs mt-1">发现</text>
      </view>
      <view class="flex flex-col items-center text-gray-400 hover:text-blue-500 transition-colors" @click="goProfile">
        <text class="fas fa-user text-xl"></text>
        <text class="text-xs mt-1">我的</text>
      </view>
    </view>

    <!-- Toast提示 -->
    <view 
      v-if="showToast"
      class="fixed top-20 left-1/2 transform -translate-x-1/2 bg-gray-800 text-white px-4 py-2 rounded-lg z-50 toast-animation"
    >
      {{ toastMessage }}
    </view>
  </view>
</template>

<script>
export default {
  name: 'PatternCollection',
  data() {
    return {
      // Toast提示
      showToast: false,
      toastMessage: '',
      toastTimeout: null,
      
      // 收藏集信息
      collectionInfo: {
        id: 1,
        name: '浪漫夜晚',
        patterns: [
          {
            id: 1,
            name: '星空夜晚',
            duration: '3:45',
            image: '/static/pattern_images/StarryNight.svg'
          },
          {
            id: 2,
            name: '玫瑰花瓣',
            duration: '2:30',
            image: '/static/pattern_images/rose.svg'
          },
          {
            id: 3,
            name: '阴阳太极',
            duration: '4:15',
            image: '/static/pattern_images/yin-yang.svg'
          },
          {
            id: 4,
            name: '螺旋星系',
            duration: '5:20',
            image: '/static/pattern_images/Spiral6.svg'
          },
          {
            id: 5,
            name: '花朵绽放',
            duration: '3:10',
            image: '/static/pattern_images/flower.svg'
          },
          {
            id: 6,
            name: '虫洞时空',
            duration: '4:45',
            image: '/static/pattern_images/wormhole.svg'
          }
        ]
      }
    }
  },
  
  onLoad(options) {
    console.log('PatternCollection page loaded with options:', options);
    // 根据传入的ID和类型加载对应的收藏集
    if (options.id) {
      const type = options.type || 'collection'; // 默认为普通收藏集
      
      if (type === 'playlist') {
        // 加载热门播放列表数据
        this.loadPlaylistCollection(options.id);
      } else {
        // 加载普通收藏集数据
        this.loadCollection(options.id);
      }
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 页面导航
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    
    goExplore() {
      uni.switchTab({
        url: '/pages/explore/index'
      })
    },
    
    goProfile() {
      uni.switchTab({
        url: '/pages/profile/index'
      })
    },
    
    // 播放单个图案
    playPattern(pattern) {
      this.showToastMessage(`正在播放 ${pattern.name}`)
      console.log('Playing pattern:', pattern)
      
      // 跳转到设备控制页面播放
      uni.navigateTo({
        url: `/pages/device/control?patternId=${pattern.id}`
      })
    },
    
    // 添加单个图案到播放列表
    addToPlaylist(pattern) {
      this.showToastMessage(`${pattern.name} 已添加到播放列表`)
      console.log('Added to playlist:', pattern)
      
      // 这里可以添加实际的添加逻辑
      // 比如调用API或更新本地存储
    },
    
    // 播放全部图案
    playAllPatterns() {
      this.showToastMessage('正在播放全部图案')
      console.log('Playing all patterns')
      
      // 跳转到设备控制页面播放全部
      uni.navigateTo({
        url: `/pages/device/control?collectionId=${this.collectionInfo.id}`
      })
    },
    
    // 添加全部图案到播放列表
    addAllToPlaylist() {
      this.showToastMessage('全部图案已添加到播放列表')
      console.log('Added all patterns to playlist')
      
      // 这里可以添加实际的添加逻辑
    },
    
    // 分享收藏集
    shareCollection() {
      this.showToastMessage('分享功能开发中')
      console.log('Share collection:', this.collectionInfo)
    },
    
    // 加载热门播放列表数据
    loadPlaylistCollection(playlistId) {
      console.log('Loading playlist collection:', playlistId);
      
      // 从本地存储获取已保存的播放列表数据
      const playlistData = uni.getStorageSync('current_playlist');
      
      if (playlistData) {
        console.log('Found playlist data in storage:', playlistData);
        
        // 转换数据格式以适应当前组件
        this.collectionInfo = {
          id: playlistData.id || playlistId,
          name: playlistData.title || playlistData.name || '热门播放列表',
          patterns: Array.isArray(playlistData.patterns) ? playlistData.patterns.map(pattern => ({
            id: pattern.id || pattern._id,
            name: pattern.name || pattern.pattern_name || '未命名图案',
            duration: pattern.duration ? this.formatPlayTime(pattern.duration) : '3:00',
            image: pattern.preview_image || pattern.thumbnail || pattern.pattern_file || '/static/pattern_images/default.svg'
          })) : []
        };
      } else {
        // 如果本地没有数据，尝试从API获取
        this.fetchPlaylistFromApi(playlistId);
      }
    },
    
    // 从API获取播放列表数据
    fetchPlaylistFromApi(playlistId) {
      console.log('Fetching playlist data from API:', playlistId);
      
      import('@/api/index.js').then(({ featuredPlaylistApi }) => {
        featuredPlaylistApi.getPlaylistDetail(playlistId).then(result => {
          if (result.errCode === 0 && result.data) {
            const playlistData = result.data;
            
            // 转换数据格式以适应当前组件
            this.collectionInfo = {
              id: playlistData.id || playlistId,
              name: playlistData.title || playlistData.name || '热门播放列表',
              patterns: Array.isArray(playlistData.patterns) ? playlistData.patterns.map(pattern => ({
                id: pattern.id || pattern._id,
                name: pattern.name || pattern.pattern_name || '未命名图案',
                duration: pattern.duration ? this.formatPlayTime(pattern.duration) : '3:00',
                image: pattern.preview_image || pattern.thumbnail || pattern.pattern_file || '/static/pattern_images/default.svg'
              })) : []
            };
            
            // 保存到本地存储
            uni.setStorageSync('current_playlist', playlistData);
          } else {
            console.error('获取播放列表详情失败:', result);
            uni.showToast({
              title: '获取播放列表详情失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error('获取播放列表详情失败:', error);
          uni.showToast({
            title: '获取播放列表详情失败',
            icon: 'none'
          });
        });
      });
    },
    
    // 格式化播放时长显示
    formatPlayTime(seconds) {
      if (!seconds) return '0:00';
      const mins = Math.floor(seconds / 60);
      const secs = Math.round(seconds % 60);
      return `${mins}:${secs.toString().padStart(2, '0')}`;
    },
    
    // 加载收藏集数据
    loadCollection(collectionId) {
      // 这里可以根据ID从API或本地存储加载数据
      // 目前使用模拟数据
      console.log('Loading collection:', collectionId)
      
      // 模拟不同收藏集的数据
      const collections = {
        1: {
          id: 1,
          name: '浪漫夜晚',
          patterns: [
            {
              id: 1,
              name: '星空夜晚',
              duration: '3:45',
              image: '/static/pattern_images/StarryNight.svg'
            },
            {
              id: 2,
              name: '玫瑰花瓣',
              duration: '2:30',
              image: '/static/pattern_images/rose.svg'
            },
            {
              id: 3,
              name: '阴阳太极',
              duration: '4:15',
              image: '/static/pattern_images/yin-yang.svg'
            }
          ]
        },
        2: {
          id: 2,
          name: '自然风景',
          patterns: [
            {
              id: 7,
              name: '山川河流',
              duration: '4:30',
              image: '/static/pattern_images/mountain.svg'
            },
            {
              id: 8,
              name: '海浪涛声',
              duration: '3:20',
              image: '/static/pattern_images/wave.svg'
            }
          ]
        }
      }
      
      if (collections[collectionId]) {
        this.collectionInfo = collections[collectionId]
      }
    },
    
    // 显示Toast提示
    showToastMessage(message) {
      this.toastMessage = message
      this.showToast = true
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.showToast = false
      }, 3000)
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }
.bg-gray-600 { background-color: #4b5563; }
.bg-gray-700 { background-color: #374151; }
.bg-gray-800 { background-color: #1f2937; }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-700 { color: #374151; }
.text-gray-800 { color: #1f2937; }
.text-gray-900 { color: #111827; }
.text-blue-500 { color: #3b82f6; }

.border-b { border-bottom-width: 1px; }
.border-t { border-top-width: 1px; }
.border { border-width: 1px; }
.border-gray-100 { border-color: #f3f4f6; }
.border-gray-200 { border-color: #e5e7eb; }

.h-screen { height: 100vh; }
.h-20 { height: 80px; }
.h-10 { height: 40px; }
.h-16 { height: 64px; }
.h-full { height: 100%; }
.w-10 { width: 40px; }
.w-16 { width: 64px; }
.w-full { width: 100%; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }

.px-4 { padding-left: 16px; padding-right: 16px; }
.px-6 { padding-left: 24px; padding-right: 24px; }
.py-2 { padding-top: 8px; padding-bottom: 8px; }
.py-3 { padding-top: 12px; padding-bottom: 12px; }
.py-4 { padding-top: 16px; padding-bottom: 16px; }
.pt-12 { padding-top: 48px; }
.pb-4 { padding-bottom: 16px; }

.mr-2 { margin-right: 8px; }
.mr-3 { margin-right: 12px; }
.mr-4 { margin-right: 16px; }
.mb-2 { margin-bottom: 8px; }
.mb-3 { margin-bottom: 12px; }
.mt-1 { margin-top: 4px; }

.rounded-lg { border-radius: 8px; }
.rounded-xl { border-radius: 12px; }
.rounded-full { border-radius: 9999px; }

.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.justify-around { justify-content: space-around; }

.text-xl { font-size: 20px; }
.text-2xl { font-size: 24px; }
.text-sm { font-size: 14px; }
.text-xs { font-size: 12px; }

.font-bold { font-weight: 700; }
.font-medium { font-weight: 500; }

.space-x-2 > * + * { margin-left: 8px; }
.space-x-3 > * + * { margin-left: 12px; }
.space-x-4 > * + * { margin-left: 16px; }
.space-y-3 > * + * { margin-top: 12px; }

.transition-colors { transition: color 0.2s ease, background-color 0.2s ease; }

.relative { position: relative; }
.fixed { position: fixed; }
.top-20 { top: 80px; }

.z-50 { z-index: 50; }

.object-cover { object-fit: cover; }

.opacity-90 { opacity: 0.9; }

.transform { transform: var(--tw-transform); }
.-translate-x-12 { --tw-translate-x: -50%; }

.left-12 { left: 50%; }

/* 自定义样式 */
.bg-gradient-to-br {
  background: linear-gradient(135deg, #8b5cf6, #ec4899);
}

.from-purple-500 { 
  background: linear-gradient(135deg, #8b5cf6, #ec4899); 
}

.hover\:text-gray-800:hover { color: #1f2937; }
.hover\:text-blue-500:hover { color: #3b82f6; }
.hover\:bg-blue-600:hover { background-color: #2563eb; }
.hover\:bg-gray-200:hover { background-color: #e5e7eb; }

/* 图案卡片动画 */
.pattern-card {
  transition: all 0.3s ease;
}

.pattern-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

/* 播放按钮动画 */
.play-button {
  transition: all 0.3s ease;
}

.play-button:hover {
  transform: scale(1.05);
}

/* Toast动画 */
.toast-animation {
  animation: toast-in 0.3s ease-out;
}

@keyframes toast-in {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

/* Font Awesome 图标 */
.fas {
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
}

.fa-chevron-left:before { content: "\f053"; }
.fa-share-alt:before { content: "\f1e0"; }
.fa-play:before { content: "\f04b"; }
.fa-plus:before { content: "\f067"; }
.fa-home:before { content: "\f015"; }
.fa-compass:before { content: "\f14e"; }
.fa-user:before { content: "\f007"; }
</style>